<!-- src/views/Home.vue -->
<template>
  <div class="home">
    <!-- 目录选择界面 - 当没有设置媒体目录时显示 -->
    <div v-if="!mediaDirectory" class="directory-selection">
      <h2>欢迎使用本地媒体浏览器</h2>
      <p>请选择您的媒体文件所在目录</p>
      
      <div class="directory-input-container">
        <el-input 
          v-model="selectedDirectory" 
          placeholder="请选择或输入媒体目录路径"
          size="large"
          :readonly="!isWebEnvironment"
        />
        <el-button 
          type="primary" 
          @click="browseDirectory" 
          size="large"
          style="margin-left: 10px;"
        >
          浏览目录
        </el-button>
        <el-button 
          type="success" 
          @click="setMediaDirectory" 
          :disabled="!selectedDirectory"
          size="large"
          style="margin-left: 10px;"
        >
          确定
        </el-button>
      </div>
      
      <p class="info-text">
        选择目录后，系统将扫描其中的图片和视频文件，并生成缩略图以供浏览。<br>
        所有元数据将存储在所选目录下的隐藏文件夹 <code>myMediaMeta</code> 中。
      </p>
      
      <div v-if="showWebWarning" class="web-warning">
        <el-alert
          title="提示"
          type="info"
          :closable="false"
          description="您正在使用Web版本，部分功能可能受限。建议使用桌面应用以获得完整体验。"
        />
      </div>
    </div>
    
    <!-- 主界面 - 当设置了媒体目录后显示 -->
    <div v-else class="main-content">
      <div class="header">
        <h1>本地媒体 - {{ mediaDirectory }}</h1>
        <div class="action-buttons">
          <el-button 
            type="info"
            @click="resetMediaDirectory"
          >
            切换目录
          </el-button>
          <el-button 
            type="primary" 
            @click="scanDirectory"
            :loading="scanning"
          >
            {{ scanning ? '扫描中...' : '重新扫描' }}
          </el-button>
          <div class="config-panel">
            <label>瀑布流列数：</label>
            <el-input-number 
              v-model="waterfallColumns" 
              :min="1" 
              :max="10" 
              @change="updateWaterfallColumns"
              size="small"
            />
          </div>
        </div>
      </div>
      
      <div 
        class="waterfall-grid" 
        :style="{'grid-template-columns': `repeat(${waterfallColumns}, minmax(0, 1fr))`}"
        ref="gridRef"
      >
        <div 
          v-for="content in contentStore.contents" 
          :key="content.id"
          class="content-card"
          @click="goToPlayer(content.id)"
        >
          <div class="thumbnail-container">
            <div v-if="content.isLoading" class="loading-overlay">
              <el-input class="loading"><Loading /></el-input>
            </div>
            <img 
              v-else-if="content.contentType === 'image'" 
              :src="getThumbnailSrc(content)" 
              :alt="content.title || content.filename"
              @error="onImageError"
              @load="onMediaLoad(content.id)"
            />
            <img 
              v-else 
              :src="getThumbnailSrc(content)" 
              :alt="content.title || content.filename"
              @error="onVideoThumbnailError($event, content)"
              @load="onMediaLoad(content.id)"
            />
          </div>
          
          <div class="content-info">
            <h3>{{ content.title || content.filename }}</h3>
            <div class="tags" v-if="content.tags && content.tags.length > 0">
              <span 
                v-for="tag in content.tags" 
                :key="tag.id" 
                class="tag"
              >
                {{ tag.name }}
              </span>
            </div>
            
            <div class="actions">
              <el-button 
                type="primary" 
                :icon="Star" 
                size="small"
                @click.stop="rateContent(content.id)"
                circle
              />
              <el-button 
                :type="content.isFavorite ? 'danger' : 'default'" 
                :icon="content.isFavorite ? StarFilled : Star" 
                size="small"
                @click.stop="toggleFavorite(content.id)"
                circle
              />
            </div>
          </div>
        </div>
      </div>
      
      <div v-if="contentStore.loading || scanning" class="loading-overlay-full">
        <el-icon class="is-loading"><Loading /></el-icon>
        <p v-if="scanning">正在扫描目录...</p>
        <p v-else>加载中...</p>
      </div>
      
      <div v-if="contentStore.error" class="error">
        {{ contentStore.error }}
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { Star, StarFilled, Loading } from '@element-plus/icons-vue';
import { useContentStore } from '../stores/content';
import { useSystemConfigStore } from '../stores/systemConfig';
import type { Content } from '../types/models';
import axios from 'axios';
import { fileSystemAPI } from '../utils/fileSystem';

const router = useRouter();
const contentStore = useContentStore();
const systemConfigStore = useSystemConfigStore();

// 目录相关状态
const mediaDirectory = ref<string | null>(null);
const selectedDirectory = ref('');
const scanning = ref(false);
const showWebWarning = ref(false);
const isWebEnvironment = ref(false);

// 瀑布流列数
const waterfallColumns = ref(3);

onMounted(async () => {
  // 检测是否在Web环境中运行
  isWebEnvironment.value = typeof window !== 'undefined' && 
    !(window as any).require && 
    !(window as any).__TAURI__;
  
  if (isWebEnvironment.value) {
    showWebWarning.value = true;
  }
  
  // 启动时不要自动加载目录，用户必须明确选择目录
  // 检查本地存储中是否保存了上次选择的目录
  const savedDirectory = localStorage.getItem('selectedMediaDirectory');
  if (savedDirectory) {
    // 如果有保存的目录，询问用户是否使用
    if (confirm('检测到上次使用的目录，是否继续使用？')) {
      mediaDirectory.value = savedDirectory;
      await initializeAfterDirectorySelection();
    }
  }
});

// 目录选择后的初始化
const initializeAfterDirectorySelection = async () => {
  // 初始化系统配置
  await systemConfigStore.initializeConfigs();
  
  // 获取瀑布流列数配置
  const config = systemConfigStore.getConfig('waterfall_columns');
  if (config) {
    waterfallColumns.value = parseInt(config.configValue) || 3;
  } else {
    // 如果配置不存在，创建默认配置
    await systemConfigStore.updateConfig('waterfall_columns', '3');
    waterfallColumns.value = 3;
  }
  
  // 初始化内容
  contentStore.fetchContents();
};

// 更新瀑布流列数配置
const updateWaterfallColumns = async (value: number) => {
  await systemConfigStore.updateConfig('waterfall_columns', value.toString());
};

// 选择媒体目录 - 完全使用原生目录选择功能
const browseDirectory = async () => {
  try {
    const selectedPath = await fileSystemAPI.showDirectoryPicker();
    
    // 检测当前运行环境
    const isNativeEnvironment = typeof window !== 'undefined' && 
      ((window as any).require || (window as any).__TAURI__);
    
    if (selectedPath) {
      // 在原生应用环境中获得了路径，自动填入输入框
      selectedDirectory.value = selectedPath;
    } else if (isNativeEnvironment) {
      // 在原生环境中但没有获得路径，可能是出错
      console.error('Failed to get directory path in native environment');
      alert('目录选择失败，请重试。');
    } else {
      // 在Web环境中，由于安全限制无法获取路径，使用提示框作为备用
      const userPath = prompt('由于浏览器安全限制，请手动输入媒体目录路径:');
      if (userPath) {
        selectedDirectory.value = userPath;
      }
    }
  } catch (error) {
    console.error('Directory picker failed:', error);
    alert('目录选择失败，请确保应用有访问文件系统的权限。');
  }
};

// 设置媒体目录
const setMediaDirectory = async () => {
  if (!selectedDirectory.value) return;
  
  try {
    const response = await axios.post('/api/directory/set-media-dir', {
      directory: selectedDirectory.value
    });
    
    if (response.status === 200) {
      mediaDirectory.value = selectedDirectory.value;
      localStorage.setItem('selectedMediaDirectory', selectedDirectory.value); // 保存到本地存储
      
      // 立即开始扫描目录
      await scanDirectory();
    }
  } catch (error) {
    console.error('Failed to set media directory:', error);
    alert('设置媒体目录失败: ' + (error as Error).message);
  }
};

// 重置媒体目录（返回到目录选择界面）
const resetMediaDirectory = async () => {
  if (confirm('确定要切换目录吗？当前的媒体目录将被取消。')) {
    mediaDirectory.value = null;
    selectedDirectory.value = '';
    contentStore.contents = []; // 清空当前内容列表
    localStorage.removeItem('selectedMediaDirectory'); // 清除本地存储的目录
  }
};

// 扫描目录
const scanDirectory = async () => {
  if (!mediaDirectory.value) return;
  
  scanning.value = true;
  try {
    const response = await axios.post('/api/directory/scan', {
      directory: mediaDirectory.value
    });
    
    if (response.status === 200) {
      // 重新加载内容
      await contentStore.fetchContents();
      
      alert(`目录扫描完成！新增了 ${response.data.newFilesCount} 个文件。`);
    }
  } catch (error) {
    console.error('Failed to scan directory:', error);
    alert('扫描目录失败: ' + (error as Error).message);
  } finally {
    scanning.value = false;
  }
};

// 跳转到播放页面
const goToPlayer = (id: number) => {
  router.push(`/player/${id}`);
};

// 处理图片加载错误
const onImageError = (e: Event) => {
  const target = e.target as HTMLImageElement;
  target.src = 'https://via.placeholder.com/300x200?text=无法加载图片';
};

// 处理视频缩略图加载错误
const onVideoThumbnailError = (e: Event, content: Content) => {
  // 如果视频缩略图加载失败，尝试使用视频文件本身
  const target = e.target as HTMLImageElement;
  target.src = `/api/contents/${content.id}/file`;
};

// 获取缩略图源URL
const getThumbnailSrc = (content: Content) => {
  if (content.thumbnailPath) {
    // 如果有缩略图路径，优先使用
    return `/api/thumbnails/${content.id}`; // 这里需要实现缩略图API
  } else if (content.filePath && content.filePath.startsWith('http')) {
    return content.filePath;
  }
  // 如果是本地路径，通过API获取
  return `/api/contents/${content.id}/file`;
};

// 媒体加载（图片/缩略图）
const onMediaLoad = (id: number) => {
  const content = contentStore.contents.find(c => c.id === id);
  if (content) {
    content.isLoading = false;
  }
};

// 评分内容
const rateContent = async (id: number) => {
  // 这里可以实现评分逻辑，例如弹出评分对话框
  await contentStore.rateContent(id, 5); // 示例：直接评5星
};

// 切换收藏
const toggleFavorite = async (id: number) => {
  await contentStore.toggleFavorite(id);
};
</script>

<style scoped>
.home {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

/* 目录选择界面 */
.directory-selection {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  padding: 2rem;
  text-align: center;
}

.directory-selection h2 {
  margin-bottom: 1rem;
}

.directory-selection p {
  margin-bottom: 2rem;
  color: #666;
}

.directory-input-container {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 1.5rem;
  width: 100%;
  max-width: 600px;
}

.directory-input-container .el-input {
  flex: 1;
}

.web-warning {
  margin-top: 1rem;
  width: 100%;
  max-width: 600px;
}

.info-text {
  max-width: 600px;
  color: #888;
  line-height: 1.6;
  text-align: center;
}

.info-text code {
  background-color: #f0f0f0;
  padding: 2px 4px;
  border-radius: 3px;
}

/* 主内容区域 */
.main-content {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.header {
  padding: 1rem;
  background-color: #f5f5f5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header h1 {
  margin: 0;
  font-size: 1.2rem;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 60%;
}

.action-buttons {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.config-panel {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.waterfall-grid {
  flex: 1;
  overflow-y: auto;
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr)); /* 默认3列，由JS动态修改 */
  gap: 1rem;
  padding: 1rem;
}

.content-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  overflow: hidden;
  cursor: pointer;
  transition: transform 0.2s, box-shadow 0.2s;
  position: relative;
}

.content-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 16px rgba(0,0,0,0.15);
}

.thumbnail-container {
  position: relative;
  width: 100%;
  height: 200px;
  overflow: hidden;
}

.thumbnail-container img,
.thumbnail-container video {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.content-info {
  padding: 0.75rem;
}

.content-info h3 {
  margin: 0 0 0.5rem 0;
  font-size: 1rem;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.tags {
  margin-bottom: 0.5rem;
}

.tag {
  display: inline-block;
  background-color: #e6f7ff;
  color: #1890ff;
  padding: 0.2rem 0.5rem;
  border-radius: 12px;
  font-size: 0.8rem;
  margin-right: 0.25rem;
}

.actions {
  display: flex;
  gap: 0.5rem;
}

.loading, .error {
  text-align: center;
  padding: 2rem;
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(255, 255, 255, 0.8);
  z-index: 10;
}

.loading-overlay-full {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: rgba(255, 255, 255, 0.8);
  z-index: 1000;
}

.loading-overlay-full p {
  margin-top: 1rem;
}
</style>